//
//  LC_VersionUpdate.m
//  LC_CY_SDK
//
//  Created by LC on 16/10/29.
//  Copyright © 2016年 LC. All rights reserved.
//

#import "LC_VersionUpdate.h"

@implementation LC_VersionUpdate
#pragma mark -- 检测更新
+ (void)versionUpdateWithAppID:(NSString *)AppID Block_URL:(Block_URL)block_URL;
{
    //时间间隔一小时
    NSDate *currentDate = [NSDate date];
    NSDate *userLastOpenDate =[[NSUserDefaults standardUserDefaults] objectForKey:@"AppTimeLastOpenDate"];
    NSTimeInterval timeBetween = [currentDate timeIntervalSinceDate:userLastOpenDate];
    if ((timeBetween / 60 / 60) <= 1) {
        return;
    }else{
        [[NSUserDefaults standardUserDefaults] setObject:currentDate forKey:@"AppTimeLastOpenDate"];
        [[NSUserDefaults standardUserDefaults] synchronize];
    }

    
    
    NSString *nowVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    
    NSString *query = [NSString stringWithFormat:@"https://itunes.apple.com/lookup?id=%@", AppID];
    query = [query stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSData *jsonData = [[NSString stringWithContentsOfURL:[NSURL URLWithString:query] encoding:NSUTF8StringEncoding error:nil] dataUsingEncoding:NSUTF8StringEncoding];
    NSError *error = nil;
    NSDictionary *results = jsonData ? [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:&error] : nil;
    
    NSArray *configData = [results valueForKey:@"results"];
    NSString *version = @"";
    for (id config in configData)
    {
        version = [config valueForKey:@"version"];
    }
    
    NSArray *array = [nowVersion componentsSeparatedByString:@"."];
    NSArray *versionArray = [version componentsSeparatedByString:@"."];
    
    for (int i = 0; i < versionArray.count ; i++) {
        if (array.count > i) {
            if ([versionArray[i] integerValue] > [array[i] integerValue]) {
                //更新
                NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/us/app/chuang-youapp/id%@?mt=8",AppID]];
                block_URL(url , version);
                return;
            }else if ([versionArray[i] integerValue] == [array[i] integerValue]){
                
            }else{
                return;
            }
        }else{
            //更新
            NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/us/app/chuang-youapp/id%@?mt=8",AppID]];
            block_URL(url , version);
            return;
        }
        
    }
    
    NSLog(@"APPStore == %f",[version floatValue]);
    NSLog(@"NOW == %f",[nowVersion floatValue]);
}

@end
